<template>
    <div class="login">
        <div class="title">
            <img src="@/assets/img/logo_white.png">
            <h2>舟道创库</h2>
        </div>
        <div class="input-box">
            <a-input type="text" placeholder="请输入账号" v-model:value="loginName" />
            <a-input type="password" placeholder="请输入密码" v-model:value="password" />
            <a-checkbox @change="onChange" :checked="checked" class="check-box">记住密码</a-checkbox>
            <button @click="login">登录</button>
        </div>
        <div class="bottom">
            <span>2022 copyright 舟道教育科技（贵阳）有限公司</span>
        </div>
    </div>
</template>

<script>
// 用于加密
const Base64 = require("js-base64").Base64

export default {
    name: 'login',
    data() {
        return {
            loginName: '',
            password: '',
            checked: false,
        };
    },
    mounted() {
        let loginName = window.localStorage.getItem("userId");
        if (loginName) {
            this.loginName = loginName;
            this.password = Base64.decode(window.localStorage.getItem("password"));// base64解密
            this.checked = true;
        }
    },
    methods: {
        // 记住密码
        onChange(e) {
            this.checked = e.target.checked;
        },
        // 登录
        async login() {
            if (this.loginName == '') {
                this.$message.warning('请输入用户名！');
                return
            }
            if (this.password == '') {
                this.$message.warning('请输入密码！');
                return
            }
            /* ------ 账号密码的存储 ------ */
            if (this.checked) {
                window.localStorage.setItem("userId", this.loginName);
                // base64加密
                window.localStorage.setItem("password", Base64.encode(this.password));
            } else {
                window.localStorage.removeItem("userId");
                window.localStorage.removeItem("password");
            }

            let res = await this.$api.user.login(this.loginName, this.password)
                .catch(function (error) {
                });
            if (res) {
                // 用户信息保存到全局
                this.$store.commit('setUser', res.data.user)
                let urlToken = res.data.token
                window.localStorage.setItem('LESSONPLAY_TOKEN', urlToken)
                this.$router.push(`/home`);
            } else {
                this.$message.error('用户名或密码错误！')
            }
        },
    }
}
</script>

<style scoped lang="scss">
@import './login.scss';
</style>
